using System;
using System.Collections.Generic;
using System.Text;
using Activa.CoolStorage;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.Services;

namespace CodeStory.Core.ObjectBusiness
{
	public sealed class SiteSettingBusiness
	{
		private SiteSettingBusiness() {

		}
		public static void LoadObject(string name, object loadedObject) {
			CSList<SiteSettingObject, Guid> list = SiteSettingObject.List("SettingName=@SettingName", "@SettingName", name);
			Dictionary<string, string> dict = new Dictionary<string, string>(list.Count);
			foreach (SiteSettingObject s in list) {
				dict[s.RegisterKey] = s.RegisterValue;
			}
			ObjectPersisteService.LoadObject(dict, loadedObject);
		}
		public static void SaveObject(string name,object savedObject) {
			Dictionary<string, string> dict = ObjectPersisteService.SaveObject(savedObject);
			foreach (KeyValuePair<string, string> pair in dict) {
				InsertOrUpdateSiteSetting(name,pair.Key, pair.Value);
			}
		}

		private static void InsertOrUpdateSiteSetting(string settingname,string key, string val) {
			//SiteSettingObject obj = SiteSettingObject.ReadUsingUniqueField("RegisterKey", key);
			SiteSettingObject obj = SiteSettingObject.ReadFirst("SettingName=@SettingName AND RegisterKey=@RegisterKey",
				"@SettingName",settingname,"@RegisterKey",key);
			if (obj == null) {
				obj = SiteSettingObject.New();
				obj.SettingName = settingname;
				obj.RegisterKey = key;
			}
			obj.RegisterValue = val;
			obj.Save();
		} 
	}
}
